package week4;

import java.util.Arrays;
import java.util.Scanner;

/**
 * 数组扩容
 * 链表会方便很多
 */
public class ArrayAdd01 {
    public static void main(String[] args) {
        arrayAdd02();
    }

    public static void arrayAdd01() {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = new int[arr1.length + 1];

        for (int i = 0; i < arr1.length ; i++) {
            arr2[i] = arr1[i];
        }

        arr2[3] = 4;
        arr1 = arr2;

        System.out.println(Arrays.toString(arr1));
    }


    // 动态扩容
    public static void arrayAdd02() {
        Scanner scanner = new Scanner(System.in);
        int[] arr1 = {1, 2, 3};

        do {
            int[] arrNew = new int[arr1.length + 1];

            // 遍历 arr 数组，依次将 arr 的元素拷贝到 arrNew 数组
            for (int i = 0; i < arr1.length; i++) {
                arrNew[i] = arr1[i];
            }

            System.out.println("请输入你要添加的元素: ");
            int addNum = scanner.nextInt();
            // 把最这个值加到最后
            arrNew[arrNew.length - 1] = addNum;
            // 让 arr1 指向 arrNew 的地址值
            arr1 = arrNew;
            // 输出看效果
            System.out.println("====arr1扩容后的元素情况====");

            for (int i = 0; i < arr1.length; i++) {
                System.out.print(arr1[i] + "\t");
            }

            // 询问用户是否继续添加
            System.out.println("是否继续添加 y/n");
            char answer = scanner.next().charAt(0);
            if ('n' == answer) {
                break;
            }
        } while (true);

        System.out.println("你退出了添加~~~~~");

    }

}
